package com.base.config;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
@EnableCaching
@ConditionalOnProperty(prefix = "spring.cache", name = "enable", havingValue = "true", matchIfMissing = false)
public class RedisCacheManagerCustomizer {

	/**
	 * 缓存默认存活时间
	 */
	@Value("${spring.cache.redis.time-to-live}")
	private Long cacheTimeToLive;
	
	/** 自定义缓存时间配置 */
	@Value("#{${cacheMap:{}}}")  
	private Map<String, Integer> cacheMap;

	@Bean
	public RedisCacheManager getRedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
		// 初始化一个RedisCacheWriter
		RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
		// 设置CacheManager的值序列化方式为json序列化
		RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
		RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
				.fromSerializer(jsonSerializer);

		RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
				.serializeValuesWith(pair)
				// 设置默认超过期时间
				.entryTtl(Duration.ofSeconds(cacheTimeToLive));

		// 设置单个缓存的超时时间
		Map<String, RedisCacheConfiguration> initialCacheConfigurations = new HashMap<>();
		if(cacheMap != null && !cacheMap.isEmpty()) {
			cacheMap.forEach((k,v) -> {
				initialCacheConfigurations.put(k, defaultCacheConfig.entryTtl(Duration.ofSeconds(v)));
			});
		}

		// 初始化RedisCacheManager
		return new RedisCacheManager(redisCacheWriter, defaultCacheConfig, initialCacheConfigurations);

	}

}
